package com.ly.mp.dal.comm.jdbc;

import java.util.Iterator;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Component;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.logging.LogFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.ly.mp.component.entities.ProcParaEntity;

@Component
public class StoredProcDataSource {
    private final PagedJdbcTemplate jdbcTemplate;

    StoredProcDataSource(PagedJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Map<String, Object> executeStoredProc(String spName, ProcParaEntity paraEntity) {
        DataSource dataSource = this.jdbcTemplate.getDataSource();
        SimpleJdbcCall simpleJdbcCall = (new SimpleJdbcCall(dataSource)).withProcedureName(spName);
        MapSqlParameterSource sqlPara = new MapSqlParameterSource();
        Map<String, Object> spOutput = null;

        try {
            Iterator var7 = paraEntity.getInRef().keySet().iterator();

            while (var7.hasNext()) {
                String key = (String) var7.next();
                sqlPara.addValue(key, paraEntity.getInRef().get(key));
            }

            if (paraEntity.getOutRef().size() > 0) {
                this.forbidLog((DruidDataSource) dataSource);
            }

            spOutput = simpleJdbcCall.execute(sqlPara);
        } catch (Exception var12) {
            throw new RuntimeException(var12);
        } finally {
            this.revertLog((DruidDataSource) dataSource);
        }

        return spOutput;
    }

    private void forbidLog(DruidDataSource ds) {
        Iterator var2 = ds.getProxyFilters().iterator();

        while (var2.hasNext()) {
            Filter filter = (Filter) var2.next();
            if (filter instanceof LogFilter && ((LogFilter) filter).isStatementExecutableSqlLogEnable()) {
                ((LogFilter) filter).setStatementExecutableSqlLogEnable(false);
            }
        }

    }

    private void revertLog(DruidDataSource ds) {
        Iterator var2 = ds.getProxyFilters().iterator();

        while (var2.hasNext()) {
            Filter filter = (Filter) var2.next();
            if (filter instanceof LogFilter && !((LogFilter) filter).isStatementExecutableSqlLogEnable()) {
                ((LogFilter) filter).setStatementExecutableSqlLogEnable(true);
            }
        }

    }
}